package com.zhugang.week13.binarysearch;

/**
 * @program algorithms
 * @description: binarySearchLastEquals
 * @author: chanzhugang
 * @create: 2022/11/25 13:31
 */
public class BinarySearchLastEquals {

    /**
     * 查找最后一个值等于给定元素的下标, 有重复元素
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bsearchLast(int[] a, int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] == target) {
                if (mid == n - 1 || a[mid + 1] != target) {
                    // 注意边界处理，mid == n-1，直接是最后一个
                    // 找到了值，但不确定是否是最后一个，所以需要往后探测一位
                    return mid;
                } else {
                    // 伪命中，还需往后探测
                    low = mid + 1;
                }
            } else if (a[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchLastEquals binarySearchLastEquals = new BinarySearchLastEquals();
        int[] a = {1, 3, 5, 6, 6, 8, 10};
        int index = binarySearchLastEquals.bsearchLast(a, a.length, 6);
        System.out.println(index);

    }
}